package com.sjms._04_创建_原型模式;

import java.io.*;
import java.util.ArrayList;

/**
 * 序列化方式实现深拷贝
 */
public class Yang_深_序列化 implements Cloneable, Serializable {
    public String name;
    public int age;
    public ArrayList<String> list;

    public Yang_深_序列化(String name, int age) {
        this.name = name;
        this.age = age;
        this.list = new ArrayList<>();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;

        try {
            //把对象输出到 流中
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            //从流中，获取字节数组
            byte[] bytes = baos.toByteArray();

            //把字节数组写入 流中
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);

            //从流中 读取对象（反序列化）
            return ois.readObject();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //        关闭流
        finally {
            try {
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                oos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                bais.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void add() {
        this.list.add(" MMM ");
    }

}
